<?php 

class SearchesController extends AppController {
    var $name = 'Searches';
    var $helpers = array('Html', 'Form');
    var $uses = array('Locum','Event','Pharmacy','Store','Vacancy','PostCode', 'Rate', 'Invite');
    var $components = array('Session');
    
    public function beforeFilter() {
        parent::beforeFilter();
        // Get my invite
     	$a_Invite = $this->Invite->v_fGetInviteByPharmacyId( $this->Session->read('User.User.id') );
     	$this->set('a_PharInvite', $a_Invite);
     	
     	// Get i am invited
     	$a_Invite = $this->Invite->v_fGetInviteByLocumId( $this->Session->read('User.User.id') );
     	$this->set('a_LocumInvite', $a_Invite);
    }
    
    function results()
    {
        
        if($this->Session->write('search_url'))
        {
            $this->Session->del('search_url');
        }
    	$user = $this->Session->read('User.User');
    	$this->set('UserType', $user['UserType'] );
        $search_url ='';
        $data = array();
        if(!empty($_REQUEST['submit']))
        {
            //Search by country
            if(!empty($_REQUEST['countryId'])){
                $search_url = '?countryId='.$_REQUEST['countryId'].'&submit=Search';
            	// UserType = 1 (Locum) => Search Vacancy
            	if( $user['UserType'] == 1 )
            	{
					$this->paginate['Vacancy'] = array(
			                    'limit' => 10,
			                    'contain' => '',
			                    'conditions' => array('Vacancy.County_id' => $_REQUEST['countryId'],'Vacancy.DateRange <>' =>''), 
			        );
			        $data = $this->paginate('Vacancy');
			        $this->set(compact('data'));     
            	}
            	
            	// UserType = 2 (Pharmacy) => Search Locum
	            if( $user['UserType'] == 2 || $user['UserType'] == 3 )
	            {
						 $this->paginate['Locum'] = array(
						                    'limit' => 10
						                    ,'contain' => ''
						                    ,'conditions' => array(
						                             'Locum.Country_id' => $_REQUEST['countryId'], 'Locum.UserType' => 1
						                    ), 'fields' => array('Locum.*','Event.*'), 
						                    'joins' => array(
						                        array(
						                            'table' => 'events'
						                            ,'type' => 'INNER'
						                            ,'alias' => 'Event'
						                            ,'conditions' => array(
						                            'Locum.id = Event.user_id'
						                            )
						                        )
						                    )
						        );			
					    						
					    	$a_Locum = $this->paginate('Locum');
					    	foreach( $a_Locum as $key=>$locum )
					    	{
					    		// Calculate rate job
					        	$a_RateJob = $this->Rate->a_fGetRateByLocumId( $locum['Locum']['id'] );
					        	$i_RateAVG = 0;
					        	$i_TotalRate = 0; 
					        	foreach ( $a_RateJob as $RateJob )
					        	{
					        		$i_TotalRate += $RateJob['Rate']['rate'];
					        	}
					        	if( count($a_RateJob) > 0 )
					        		$i_RateAVG = round( $i_TotalRate/count($a_RateJob) );	
					        	
					        	$locum['Locum']['i_RateAVG'] = $i_RateAVG;
					        	$a_Locum[$key] = $locum;
					    	}
						    $this->set('a_Locum', $a_Locum);
	            }
	            
				$this->set('sz_params', "countryId={$_REQUEST['countryId']}&submit=Search");
            }
            
            //Search by post code
            if(!empty($_REQUEST['radius'])){
                 $search_url ='?radius='.$_REQUEST['radius'].'&submit=Search';
                 
            	// Get All PostCodes
	            $a_AllPostCode = $this->PostCode->a_fGetAllPostCode();
            	// UserType == 1 (Locum)
                if( $user['UserType'] == 1 )
                {
                	$a_Vacancies = array();
                	$sz_PostCodeLocum = $user['Postcode'];
                    $sz_PostCodeStandardLocum = $this->getStandardPostcode($sz_PostCodeLocum);
                	$a_PostCodeLocum = $this->PostCode->a_fGetPostCode( $sz_PostCodeStandardLocum );
                	$a_SearchPostCode = array();
                	$sz_SearchPostCode = "";
                	if ( $a_PostCodeLocum )
                	{
						foreach ( $a_AllPostCode as $PostCode )
						{
							
							$distance = $this->getDistance($a_PostCodeLocum['PostCode']['latitude'], $a_PostCodeLocum['PostCode']['longitude'], $PostCode['PostCode']['latitude'], $PostCode['PostCode']['longitude'], 'miles');
                           
							if ( $distance <= $GLOBALS['Radius'][$_REQUEST['radius']] )
							{
								$a_SearchPostCode[] = strtoupper($PostCode['PostCode']['postcode']);
							}
        
						}
                        
	                	if ( count( $a_SearchPostCode ) > 0 )
						{
							$a_VacancyId = array();
							foreach($a_SearchPostCode as $sz_postcode)
							{
								$vacancyId = $this->Vacancy->find('all',array('fields'=>'id','conditions'=>array('Vacancy.Postcode LIKE'=>$sz_postcode.'%')));
								
								if($vacancyId)
								{
									foreach ($vacancyId as $id)
									{
										$a_VacancyId[] = $id['Vacancy']['id'];
									}
								}
							}
							if($a_VacancyId)
							{
								$a_VacancyId = array_unique($a_VacancyId);
								$this->paginate['Vacancy'] = array(
												        'conditions' => array('Vacancy.id' => $a_VacancyId,'Vacancy.DateRange <>' =>''),
												        'limit' => 10
						    						);
						    	
						    	$data = $this->paginate('Vacancy');
							}
						}
                	}
					
					$this->set('data', $data);
                }
            	// UserType == 3 (Store) => search Locum
                if( $user['UserType'] == 3 )
                {
                	$a_Locum = array();
                	$sz_PostCodePhar = $user['Postcode'];
                    $sz_PostCodeStandardPhar = $this->getStandardPostcode($sz_PostCodePhar);
                	$a_PostCodePhar = $this->PostCode->a_fGetPostCode( $sz_PostCodeStandardPhar );
                	$a_SearchPostCode = array();
                	if ( $a_PostCodePhar )
                	{
						foreach ( $a_AllPostCode as $PostCode )
						{
							$distance = $this->getDistance($a_PostCodePhar['PostCode']['latitude'], $a_PostCodePhar['PostCode']['longitude'], $PostCode['PostCode']['latitude'], $PostCode['PostCode']['longitude'], 'miles');
							if ( $distance <= $GLOBALS['Radius'][$_REQUEST['radius']] )
							{
								$a_SearchPostCode[] = strtoupper($PostCode['PostCode']['postcode']);
							}
						}
	                	if ( count( $a_SearchPostCode ) > 0 )
	                	{	

		                	$a_LocumIds = array();
							foreach($a_SearchPostCode as $sz_postcode)
							{
								$a_LocumId = $this->Locum->find('all',array('fields'=>'id','conditions'=>array('Locum.Postcode LIKE'=>$sz_postcode.'%')));
								
								if($a_LocumId)
								{
									foreach ($a_LocumId as $id)
									{
										$a_LocumIds[] = $id['Locum']['id'];
									}
								}
							}
	                		
	                		if($a_LocumIds)
							{
								$a_LocumIds = array_unique($a_LocumIds);
								$this->paginate['Locum'] = array(
						                    'limit' => 10
						                    ,'contain' => ''
						                    ,'conditions' => array(
						                             'Locum.id' => $a_LocumIds, 'Locum.UserType' => 1
						                    ), 'fields' => array('Locum.*','Event.*'), 
						                    'joins' => array(
						                        array(
						                            'table' => 'events'
						                            ,'type' => 'INNER'
						                            ,'alias' => 'Event'
						                            ,'conditions' => array(
						                            'Locum.id = Event.user_id'
						                            )
						                        )
						                    )
						        );
					    		$a_Locum = $this->paginate('Locum');	
							}
						}
                	}
                	
                	foreach( $a_Locum as $key=>$locum )
			    	{
			    		// Calculate rate job
			        	$a_RateJob = $this->Rate->a_fGetRateByLocumId( $locum['Locum']['id'] );
			        	$i_RateAVG = 0;
			        	$i_TotalRate = 0; 
			        	foreach ( $a_RateJob as $RateJob )
			        	{
			        		$i_TotalRate += $RateJob['Rate']['rate'];
			        	}
			        	if( count($a_RateJob) > 0 )
			        		$i_RateAVG = round( $i_TotalRate/count($a_RateJob) );	
			        	
			        	$locum['Locum']['i_RateAVG'] = $i_RateAVG;
			        	$a_Locum[$key] = $locum;
			    	}  
                	$this->set('a_Locum', $a_Locum);
                }
                $this->set('sz_params', "radius={$_REQUEST['radius']}&submit=Search");
            }
            
            $this->Session->write('search_url',$search_url);
            $this->set('submit', $_REQUEST['submit']);
        }
    }
	private function getDistance($lat1, $long1, $lat2, $long2, $unit)
	{
		
	  if($unit=="miles"){
	      $earth = 3960; //miles
	  }else{
	     $earth = 6371; //kilometres
	  }
	
		//From co-ordinates
		$lat1 = deg2rad($lat1);
		$long1= deg2rad($long1);
	
		//To co-ordinates
		$lat2 = deg2rad($lat2);
		$long2= deg2rad($long2);
	
		// The Haversine Formula
		$dlong=$long2-$long1;
		$dlat=$lat2-$lat1;
	
		$sinlat=sin($dlat/2);
		$sinlong=sin($dlong/2);
	
		$a=($sinlat*$sinlat)+cos($lat1)*cos($lat2)*($sinlong*$sinlong);
	
		$c=2*asin(min(1,sqrt($a)));
	
		$d=round($earth*$c);
	
		return $d;
	}
 	
	function getJson($id = null)
    {

         Configure::write('debug', 0);
         $this->autoRender = false;
         $this->layout =  false;
         $sz_StartEvent ='[';
         $sz_EndEvent =']';
           $a_Events = $this->Event->a_fGetEvents($id); 

           if($a_Events)
           {
               $a_Event = explode(',',$a_Events['Event']['date']);
               $i=1;
               $n= count($a_Event);
               foreach($a_Event as $k=>$event){
                  if($i < $n)
                    $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'},';
                  else
                     $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
                  $i++;
               }
           }
        echo $sz_StartEvent.$sz_EndEvent;
        $this->render(false);
    }
    
	function getJsonVacancy($id = null)
	{
		Configure::write('debug', 0);
		$this->autoRender = false;
		$this->layout =  false;
		$sz_StartEvent ='[';
		$sz_EndEvent =']';
		$this->set('id',$id);
		$a_Events = $this->Vacancy->find('first',array('fields'=>'DateRange','conditions'=>array('id'=>$id)));
		if($a_Events)
		{
			$a_Event = explode(',',$a_Events['Vacancy']['DateRange']);
			 
			$i=1;
			$n= count($a_Event);
			foreach($a_Event as $k=>$event){
				if($i < $n)
				$sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'},';
				else
				$sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
				$i++;
			}
		}


		echo $sz_StartEvent.$sz_EndEvent;
		$this->render(false);
	}
	
	function getStandardPostcode($the_sz_postCode)
	{
		$postcode = strtoupper(trim($the_sz_postCode));
		#Remove any spaces
		$postcode = str_replace(" ","",$postcode);
		
		#Trim the last 3 characters off the end
		return substr($postcode,0,strlen($postcode)-3);
	}
}
?>